<?php
namespace User\Controller;
use User\Controller\BaseController;
class OrdersController extends BaseController {
    private $O;
    private $R;
    private $S;
    public function _initialize(){
        $this->O = M("orders");
        $this->R = M("orders_rooms");
        $this->S = M("orders_senic");
        Vendor("Alipay.CoreFunction");
        Vendor("Alipay.Md5Function");
        Vendor("Alipay.Submit");
        Vendor("Alipay.Notify");
    }
    /*
    *   添加订单
    */
    public function add(){
        $orders_data = $this->O->create();
        $pid = I("pid");
        if($orders_data["users_id"] == "" || $orders_data["type"] == "" || $pid == ""){
            redirect("/Home/Index/index",0,"");
        }
        $orders_data["order_time"] = time();
        $orders_data["oid"] = date("YmdHis", $orders_data["order_time"]).rand(10, 99);
        if($orders_data["type"] == 0){
            $orders_details = $this->R->create();
            $orders_details["checkin"] = strtotime($orders_details["checkin"]);
            $orders_details["checkout"] = strtotime($orders_details["checkout"]);
            $orders_details["rooms_id"] = $pid;
            $room = M("rooms")->where("id=".$pid)->find();
            $orders_data["price"] = $room["price"];
            $orders_details["orders_id"] = $this->O->data($orders_data)->add();
            $res = $this->R->data($orders_details)->add();
        }
        else{
            $orders_details = $this->S->create();
            $orders_details["day"] = strtotime($orders_details["day"]);
            $orders_details["senic_id"] = $pid;
            $senic = M("senic")->where("id=".$pid)->find();
            $orders_data["price"] = $senic["adult"] * $orders_details["adult_nums"] + $senic["child"] * $orders_details["child_nums"];
            $orders_details["orders_id"] = $this->O->data($orders_data)->add();
            $res = $this->S->data($orders_details)->add();
        }
        // $this->info($orders_details["orders_id"]);
        $this->redirect('Orders/info', array("oid" => $orders_details["orders_id"]), 0, '页面跳转中...');
    }
    /*
    *   支付订单
    */
    public function info($oid = ""){
        if($oid == ""){
            redirect("/Home/Index/index",0,"");
        }
        $order = $this->O->where("id=".$oid)->find();
        if($order["type"] == 0){
            $details = $this->R->alias("oro")->where("orders_id=".$oid)
                        ->join(array(
                            "left join __ROOMS__ r on oro.rooms_id=r.id",
                            "left join __HOTELS__ h on r.hotels_id=h.id",
                            "left join __ROOMS_TYPE__ t on t.id=r.type"
                        ))
                        ->field(array(
                            "oro.*",
                            "t.name"=>"roomtype",
                            "h.name"=>"hotel"
                        ))
                        ->find();
        }
        else{
            $details = $this->S->alias("os")->where("orders_id=".$oid)
                        ->join(array(
                            "left join __SENIC__ s on os.senic_id=s.id",
                        ))
                        ->field(array(
                            "os.*",
                            "s.name"=>"senic",
                        ))
                        ->find();
        }
        $userinfo = M("users")->where("id=".$order["users_id"])->find();
        $this->assign("userinfo", $userinfo);
        $this->assign("order", $order);
        $this->assign("details", $details);
        echo R("Home/Navlink/index");
        $this->display("info");
    }
    public function alipayApi(){
        $alipay_config = C("alipay_config");
        /**************************请求参数**************************/
        //商户订单号，商户网站订单系统中唯一订单号，必填
        $out_trade_no = $_POST['WIDout_trade_no'];
        //订单名称，必填
        $subject = $_POST['WIDsubject'];
        //付款金额，必填
        $total_fee = $_POST['WIDtotal_fee'];
        //商品描述，可空
        $body = $_POST['WIDbody'];
        /************************************************************/
        //构造要请求的参数数组，无需改动
        $parameter = array(
            "service"       => $alipay_config['service'],
            "partner"       => $alipay_config['partner'],
            "seller_id"  => $alipay_config['seller_id'],
            "seller_email"  => $alipay_config['seller_email'],
            "payment_type"  => $alipay_config['payment_type'],
            "notify_url"    => $alipay_config['notify_url'],
            "return_url"    => $alipay_config['return_url'],
            "anti_phishing_key"=>$alipay_config['anti_phishing_key'],
            "exter_invoke_ip"=>$alipay_config['exter_invoke_ip'],
            "out_trade_no"  => $out_trade_no,
            "subject"   => $subject,
            "total_fee" => $total_fee,
            "body"  => $body,
            "_input_charset"    => trim(strtolower($alipay_config['input_charset']))
            //其他业务参数根据在线开发文档，添加参数.文档地址:https://doc.open.alipay.com/doc2/detail.htm?spm=a219a.7629140.0.0.kiX33I&treeId=62&articleId=103740&docType=1
            //如"参数名"=>"参数值"
        );
        //建立请求
        $alipaySubmit = new \AlipaySubmit($alipay_config);
        $html_text = $alipaySubmit->buildRequestForm($parameter,"get", "确认");
        echo $html_text;
    }
    /*
    *   支付宝订单通知
    */
    public function alipayNotify(){
        $alipay_config = C("alipay_config");
        $alipayNotify = new \AlipayNotify($alipay_config);
        $verify_result = $alipayNotify->verifyReturn();
        if($verify_result) {//验证成功
            //请在这里加上商户的业务逻辑程序代码
            //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
            //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表
            //商户订单号
            $out_trade_no = $_GET['out_trade_no'];
            //支付宝交易号
            $trade_no = $_GET['trade_no'];
            //交易状态
            $trade_status = $_GET['trade_status'];
            if($_GET['trade_status'] == 'TRADE_FINISHED' || $_GET['trade_status'] == 'TRADE_SUCCESS') {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序
                $oid = I("out_trade_no");
                $this->O->where("oid=".$oid)->data(array("status"=>1))->save();
                redirect("/User/Index/index",0,"");
            }
            //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
        }
        else {
            //验证失败
            //如要调试，请看alipay_notify.php页面的verifyReturn函数
            redirect("/User/Index/orders",0,"");
        }
    }
    /*
    *   订单详情页
    */
    public function index(){
        echo R("Home/Navlink/index");
        $uid = session("id");
        if($uid == ""){
            redirect("/User/Index/index",0,"");
        }
        $orders = $this->O->where("status between 0 and 1 and users_id=".$uid)->select();
        $orders_details = array();
        foreach($orders as $k=>$v){
            if($v["type"] == 0){
                $orders_details[$k] = $this->R->alias("oro")->where("orders_id=".$v["id"])->join("left join __ROOMS__ r on oro.rooms_id=r.id left join __HOTELS__ h on r.hotels_id=h.id left join __ROOMS_TYPE__ t on r.type=t.id")->field(array("oro.*","h.name"=>"hotel","t.name"=>"type"))->find();
            }
            elseif($v["type"] == 1){
                $orders_details[$k] = $this->S->alias("os")->where("orders_id=".$v["id"])->join("left join __SENIC__ s on os.senic_id=s.id left join __THEME__ t on s.theme_id=t.id")->field(array("os.*","s.name"=>"senic","t.value"=>"theme"))->find();
            }
            else{
                $orders_details[$k] = array();
            }
        }
        $this->assign("orders", $orders);
        $this->assign("details", $orders_details);
        $this->display();
    }
    /*
    *   删除订单
    */
    public function del(){
        $id = I("id");
        if($id == ""){
            redirect("/User/Orders",0,"");
        }
        $res = $this->O->where("id=".$id)->data(array("status"=>2))->save();
        if($res){
            redirect("/User/Orders",0,"");
        }
        else{
            redirect("/User/Orders",0,"");
        }
    }
}